package cn.smart.pagex.aop;

import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
@ConditionalOnProperty(prefix = "cn.smart.pageX", name = "enable", havingValue = "true")
@Slf4j
public class PageXAop {
    //切点
    @Pointcut("@annotation(cn.smart.core.annotation.PageX)")
    public void point() {
        System.out.println("PageX");
    }
    //前置通知
    @Before("point()")
    public void before() {
        System.out.println("PageX before");
    }
    //环绕通知
    @Around("point()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        log.debug("pageX-before");
        // 获取当前请求的RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 将RequestAttributes转换为ServletRequestAttributes
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        // 获取HttpServletRequest
        HttpServletRequest request = servletRequestAttributes.getRequest();
        // 获取pageNum参数
        String pageNum = request.getParameter("pageNum");
        // 获取pageSize参数
        String pageSize = request.getParameter("pageSize");
        // 如果pageNum和pageSize都不为空，则开启分页
        if(ObjectUtil.isNotEmpty(pageNum) && ObjectUtil.isNotEmpty(pageSize)){
            PageHelper.startPage(Integer.valueOf(pageNum),Integer.valueOf(pageSize));
        }
        Object value = joinPoint.proceed();
        log.debug("pageX-after");
        return value;
    }
    //后置通知
    @After("point()")
    public void after() {
        System.out.println("PageX after");
    }
}
